package com.baosight.risk.service.riim.impl;

import com.baosight.risk.api.riim.RiimRiskAssignmentService;
import com.baosight.risk.base.service.BaseServiceImpl;
import com.baosight.risk.common.bean.BeanUtils;
import com.baosight.risk.common.utils.StringUtils;
import com.baosight.risk.mapper.riim.RiimRiskAssignmentMapper;
import com.baosight.risk.service.riim.entity.RiimRiskAssignment;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author RayWade
 * @create 2019 - 08 - 20 16:58
 */
@Service
@Slf4j
public class RiimRiskAssignmentServiceImpl extends BaseServiceImpl<RiimRiskAssignment>
        implements RiimRiskAssignmentService {

    @Autowired
    private RiimRiskAssignmentMapper assignmentMapper;

    @Override
    public Integer saveAssignment(RiimRiskAssignment assignment) {
        if (StringUtils.isEmpty(assignment.getId())) {
            Integer rowOrder;
            Integer maxRowOrder = assignmentMapper.queryMax(assignment.getImportGuid());
            if (maxRowOrder == null) {
                rowOrder = 1;
            } else {
                rowOrder = Integer.valueOf(maxRowOrder) + 1;
            }
            assignment.setRowOrder(rowOrder);
            assignment = (RiimRiskAssignment) BeanUtils.initBean(assignment);
            return assignmentMapper.insert(assignment);
        } else {
            assignment = (RiimRiskAssignment) BeanUtils.updateBean(assignment);
            return update(assignment);
        }
    }

    @Override
    public Integer deleteAssignment(List<String> ids) {
        ids.forEach(id ->
                assignmentMapper.deleteByPrimaryKey(id));
        return 1;
    }

    @Override
    public void updateRowOrder(RiimRiskAssignment assignment) {
        List<RiimRiskAssignment> list = assignmentMapper.selectByImportGuid(assignment.getImportGuid());
        if (CollectionUtils.isNotEmpty(list)) {
            List<String> ids = list.stream().map(RiimRiskAssignment::getId).collect(Collectors.toList());
            int i = ids.indexOf(assignment.getId());
            RiimRiskAssignment assignment1 = get(assignment.getId());
            if ("up".equals(assignment.getExt1())) {
                i--;
            } else {
                i++;
            }
            if(i < ids.size() && i >= 0){
                RiimRiskAssignment assignment2 = get(ids.get(i));
                int rowOrder1 = assignment1.getRowOrder();
                int rowOrder2 = assignment2.getRowOrder();
                assignment1.setRowOrder(rowOrder2);
                update(assignment1);
                assignment2.setRowOrder(rowOrder1);
                update(assignment2);
            }
        }
    }
}
